//
//  MyShowLoginViewController.m
//  BosidengIphone
//
//  Created by  on 11-12-30.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyShowLoginViewController.h"
#import "AppDelegate.h"
#import "ASIFormDataRequest.h"
#import "RegexKitLite.h"
#import "CustomData.h"
#import "MyShowRegistrationViewController.h"
#import "MainViewController.h"

@implementation MyShowLoginViewController
@synthesize labNaviTitle;
@synthesize labTitle;
@synthesize labMessage;
@synthesize labPhone;
@synthesize labPassword;
@synthesize btnRegister;
@synthesize txtPhone;
@synthesize txtPassword;
@synthesize btnLogin;
@synthesize waitView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [waitView release];
    [labNaviTitle release];
    [labTitle release];
    [labMessage release];
    [labPhone release];
    [labPassword release];
    [btnRegister release];
    [txtPhone release];
    [txtPassword release];
    [btnLogin release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //self.labNaviTitle.text = [NSString stringWithFormat:@"立即秀一下 > 登录"];
    self.labTitle.text = [AppDelegate getLanguageString:@"show_login_title"];
    self.labMessage.text = [AppDelegate getLanguageString:@"show_login_message"];
    self.labPhone.text = [AppDelegate getLanguageString:@"show_login_phone"];
    self.labPassword.text = [AppDelegate getLanguageString:@"show_login_password"];
    [self.btnLogin setTitle:[AppDelegate getLanguageString:@"show_login_title"] forState:UIControlStateNormal];
    [self.btnRegister setTitle:[AppDelegate getLanguageString:@"show_regist_btn_message"] forState:UIControlStateNormal];
    txtPhone.text = @"";
	txtPassword.text = @"";
    txtPhone.delegate = self;
    txtPassword.delegate = self;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.labNaviTitle = nil;
    self.labTitle = nil;
    self.labMessage = nil;
    self.labPhone = nil;
    self.labPassword = nil;
    self.btnRegister = nil;
    self.txtPhone = nil;
    self.txtPassword = nil;
    self.btnLogin = nil;
    self.waitView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    int tag = textField.tag;
    if (101 == tag) {
        [txtPassword becomeFirstResponder];
    } else {
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	NSLog(@"buttonIndex=%d", buttonIndex);
	[(MainViewController *)mainViewController popViewController];
}

- (IBAction)backgroundTab:(id)sender {
    [txtPhone resignFirstResponder];
    [txtPassword resignFirstResponder];
}

- (void)showCheckNullMessge:(NSString *)message {
	UIAlertView *infoView = [[UIAlertView alloc] 
							 initWithTitle:@""
							 message:[NSString stringWithFormat:@"%@%@", [AppDelegate getLanguageString:message], [AppDelegate getLanguageString:@"message_check_null"]]
							 delegate:nil 
							 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
							 otherButtonTitles:nil];
	[infoView show];
	[infoView release];
}

- (void)showCheckIllegalMessge:(NSString *)message {
	UIAlertView *infoView = [[UIAlertView alloc] 
							 initWithTitle:@""
							 message:[NSString stringWithFormat:@"%@%@", [AppDelegate getLanguageString:message], [AppDelegate getLanguageString:@"message_check_illegal"]]
							 delegate:nil 
							 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
							 otherButtonTitles:nil];
	[infoView show];
	[infoView release];
}

- (void)showMessge:(NSString *)message {
	UIAlertView *infoView = [[UIAlertView alloc] 
							 initWithTitle:@""
							 message:message
							 delegate:nil 
							 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
							 otherButtonTitles:nil];
	[infoView show];
	[infoView release];
}

- (IBAction)userLogin:(id)sender {
    
	NSString *phone = txtPhone.text;
	if ([phone isEqualToString:@""]) {
		[self showCheckNullMessge:@"show_login_phone"];
		return;
	}
    
	BOOL result = [phone isMatchedByRegex:@"\\b([0-9\\-]+)\\b"];
	if (!result) {
		[self showCheckIllegalMessge:@"show_login_phone"];
		return;
	}
    
    NSString *password = txtPassword.text;
	if ([password isEqualToString:@""]) {
		[self showCheckNullMessge:@"show_login_password"];
		return;
	}
	
	[waitView startAnimating];
	btnLogin.enabled = NO;
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/Login.ashx", [AppDelegate serviceUrl]]];
    ASIFormDataRequest *detectPost = [[ASIFormDataRequest alloc] initWithURL:url];
    [detectPost addPostValue:phone forKey:@"txt_Account"];
    [detectPost addPostValue:password forKey:@"txt_Password"];
    [detectPost addPostValue:[AppDelegate getLanguage] forKey:@"txt_Language"];
    [detectPost setDelegate:self];
    [detectPost setDidFinishSelector:@selector(requestComplete:)];
    [detectPost setDidFailSelector:@selector(requestFailed:)];
    [requestQueue addOperation:detectPost];
	[detectPost release];
}

- (void)requestComplete:(ASIFormDataRequest *)request {
	NSString *result = [request responseString];
    if ([result rangeOfString:@"html"].length > 0) {
        [waitView stopAnimating];
        btnLogin.enabled = YES;
		[self showMessge:@"Login Failed!"];
        NSLog(@"Login Failed! result=%@", result);
        return;
    }
    
	NSArray *resultInfos = [result componentsSeparatedByString:@"|"];
    NSString *resultCode = [resultInfos objectAtIndex:0];
    NSString *resultMessage = [resultInfos objectAtIndex:1];
	if ([@"1" isEqualToString:resultCode]) {
        NSLog(@"Post Login Request Success! result=%@", result);
        NSString *customId = [resultInfos objectAtIndex:2];
        CustomData *custom = (CustomData *)[CustomData findFirstByCriteria:@"WHERE row_id=1", customId];
        if (custom == nil) {
            custom = [[[CustomData alloc] init] autorelease];
            custom.rowId = 1;
        }
        custom.customId = customId;
        custom.phone = txtPhone.text;
        custom.password = txtPassword.text;
        [custom save];
        
        txtPhone.text = @"";
		txtPassword.text = @"";
        UIAlertView *infoView = [[UIAlertView alloc] 
                                 initWithTitle:@""
                                 message:resultMessage
                                 delegate:self 
                                 cancelButtonTitle:[AppDelegate getLanguageString:@"common_button_close"]
                                 otherButtonTitles:nil];
        [infoView show];
        [infoView release];
	} else {
		[self showMessge:resultMessage];
        NSLog(@"Post Login Request Failed! result=%@", result);
	}
    [waitView stopAnimating];
	btnLogin.enabled = YES;
}

- (void)requestFailed:(ASIFormDataRequest *)request {
    [self showMessge:@"proposals_submit_failed"];
    NSLog(@"Post Request Failed! error=%@", [request error]);
    [waitView stopAnimating];
	btnLogin.enabled = YES;
}

- (IBAction)showRegister:(id)sender {
    [(MainViewController *)mainViewController popViewController];
    MyShowRegistrationViewController *viewController = [[MyShowRegistrationViewController alloc] initWithNibName:@"MyShowRegistrationViewController" bundle:nil];
    [(MainViewController *)mainViewController pushViewController:viewController];
    [viewController release];
}

@end
